package com.mrobuy.jd.product;

import com.Application;
import com.gavel.database.SQLExecutor;
import com.gavel.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.request.supplier.VcItemNewProductCreateRequest;
import com.jd.open.api.sdk.request.supplier.VcItemOldProductUpdateRequest;
import com.jd.open.api.sdk.response.supplier.VcItemNewProductCreateResponse;
import com.jd.open.api.sdk.response.supplier.VcItemOldProductUpdateResponse;
import com.jd.service.JDIntroService;
import com.jd.service.JDPictureService;
import com.mrobuy.jd.JdClientFactory;
import com.mrobuy.jdvc.entity.VCCateBrand;
import com.mrobuy.jdvc.entity.VCItem;
import com.mrobuy.jdvc.entity.VCProduct;
import com.mrobuy.jdvc.entity.VCProductInfo;
import com.mrobuy.jdvc.service.ShelvesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ImportResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.jd.service.impl.JDIntroServiceImpl;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Component
public class VCProductUpdate {

    private static Logger LOG = LoggerFactory.getLogger(JDPictureService.class);

    @Autowired
    private  JDIntroService jdIntroService;

    @Autowired
    private ShelvesService shelvesService;

    public static void main(String[] args) throws Exception {

//        applicationContext = SpringApplication.run(VCProductUpdate.class, args);
//
//        VCProductUpdate pu = new VCProductUpdate();
//        pu.jdIntroService = new JDIntroServiceImpl();
//
//        pu.update("100023660898");
//
//        System.out.println("Done!");
    }


//    @Bean
//    public VCProductUpdate restTemplate() {
//
//        try{
//        VCProductUpdate pu = new VCProductUpdate();
//        pu.update("100023660898");
//
//        System.out.println("Done!");
//        return new VCProductUpdate();
//        }catch(Exception e){
//            LOG.error(e.getMessage(), e);
//            return null;
//        }
//    }
//
//    @Bean
//    public JDIntroService JDIntroService() {
//
//        try{
//
//            return new JDIntroServiceImpl();
//        }catch(Exception e){
//            LOG.error(e.getMessage(), e);
//            return null;
//        }
//    }
    public  void update() throws Exception {

//
//        if ( StringUtils.isBlank(wareId) ) {
//            throw  new RuntimeException("WareId为空, 跳过！");
//        }
//
//        VCProductInfo vcProductInfo = SQLExecutor.executeQueryBean("select * from VC_PRODUCT_INFO where WAREID = ? ", VCProductInfo.class, wareId);
//        if ( vcProductInfo==null ) {
//            throw  new RuntimeException("[VC_PRODUCT_INFO]商品记录[" + wareId + "]为空, 跳过！");
//        }

        // 2: 可上柜; 1: 上柜; 0: 下柜
//        if ( vcProductInfo.getSaleState()==1 ) {
//            throw  new RuntimeException("商品[Wareid: " + wareId + "]已上柜, 不可修改！");
//        }

         List<VCProduct>  vcProducts = SQLExecutor.executeQueryBeanList("select * from VC_PRODUCT", VCProduct.class);
//        if ( vcProduct==null ) {
//            throw  new RuntimeException("[VC_PRODUCT]商品记录[" + wareId + "]为空, 跳过！");
//        }
//
//
//        List<VCItem> vcItems = SQLExecutor.executeQueryBeanList("select * from VC_ITEM where WAREID = ?", VCItem.class, wareId);
//        if ( vcItems==null || vcItems.size()==0 ) {
//            throw  new RuntimeException("[VC_ITEM]商品ITEM记录[" + wareId + "]为空, 跳过！");
//        }


//        System.out.println("Product: " + vcProduct.getName());
//
//        for (VCItem vcItem : vcItems) {
//            System.out.println("\t" + vcItem.getSkuName());
//        }

//        if ( vcProductInfo.getIsGaea()==1 ) {
//            updateGaea(vcProduct, vcItems);
//        } else {
//            update(vcProduct, vcItems);
//        }
        for (VCProduct vcProduct : vcProducts) {

            try {
                shelvesService.updateShelves(vcProduct);
            } catch (Exception e) {
                System.out.println("上架异常: " + e.getMessage());
            }
        }
    }


    /**
     * 更新 盖亚商品
     *
     * @throws Exception
     */
    private  void updateGaea(VCProduct product,  List<VCItem> items) throws Exception {

        LOG.info("333333", items);
        JdClient jdClient = JdClientFactory.jdClient();


        VcItemOldProductUpdateRequest request = new VcItemOldProductUpdateRequest();

        request.setWareId(product.getWareId());
        request.setName(product.getName());
        request.setCid1(Integer.parseInt(product.getCid1()));
        if(product.getLeafcid() != null && product.getLeafcid().length()!= 0) {
            request.setLeafCid(Integer.parseInt(product.getLeafcid()));
        }
        request.setBrandId(Integer.parseInt(product.getBrandid()));
        request.setZhBrand(product.getZhbrand());
        request.setEnBrand(product.getEnbrand());

        request.setTel(product.getTel());
        request.setWebSite(product.getWebsite());
        request.setOriginalPlace(product.getOriginalplace());
        request.setWarranty(product.getWarranty());

        request.setSalerCode(product.getSalercode());
        request.setPurchaserCode(product.getPurchasercode());

        request.setPkgInfo(product.getPkginfo()); // 包装清单（格式：USB线 × 1、AV线 × 1、配带 × 1、说明书 × 1、保修卡 × 1 ，最多可录入20000个字符）


        // request.setItemNum("");

//        request.setIntroHtml(product.getIntrohtml());
//        request.setIntroMobile(product.getIntromobile());

        System.out.println(jdIntroService);
        // TODO  商品介绍
        request.setIntroHtml(jdIntroService.buildPCIntroHtml2(items));            // 	PC端代码录入的商品介绍
        request.setIntroMobile(jdIntroService.buildMobileIntroHtml2(items));      // 	Mobile端代码录入的商品介绍


        try {
            if (product.getVideoid() != null && product.getVideoid().trim().length() > 0) {
                request.setVideoId(Long.parseLong(product.getVideoid()));
            }
        }catch(Exception e){
        }

        request.setDangerValue(product.getDangervalue());
        request.setSkuUnit(product.getSkuunit());

        try {
            if ( product.getStoreproperty()!=null && product.getStoreproperty().trim().length() > 0 ) {
            request.setStoreProperty(Integer.parseInt(product.getStoreproperty()));
        }
        }catch(Exception e){
        }

        request.setDesignConcept(product.getDesignconcept());
        request.setHasTransferElecCode(product.getHastransfereleccode());
        request.setAfterSaleDesc(product.getAftersaledesc());

        request.setWreadme(product.getWreadme());


//        request.setPacking(Integer.parseInt(product.getPacking())); // 包装规格（[1×N]请填写N的值）
//        request.setPackType(Integer.parseInt(product.getPacktype())); // 1	特殊属性（1:普通商品，2:易碎品，3:裸装液体，4:带包装液体，5:按原包装出库）

        request.setSkuUnit(product.getSkuunit()); // 销售单位（必须为VC接口提供的销售单位）


        VcItemOldProductUpdateResponse response = jdClient.execute(request);

        System.out.println(new Gson().toJson(response));

    }

    /**
     * 更新 非盖亚商品
     *
     * @throws Exception
     */
    private  void update(VCProduct product,  List<VCItem> items) throws Exception {

        JdClient jdClient = JdClientFactory.jdClient();


        VcItemOldProductUpdateRequest request = new VcItemOldProductUpdateRequest();

        VcItemOldProductUpdateResponse response = jdClient.execute(request);

        System.out.println(new Gson().toJson(response));

    }

}
